/**
 * Copyright (C)  2011 Kent Tong <freemant2000@yahoo.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.ttdev.ecofoods;

import java.text.MessageFormat;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TextView;

public class MainAct extends Activity {
	private static final String KEY_KEYWORD = "keyword";
	private static final int DLG_ABOUT_PROGRAM = 0;
	private static final int DLG_ABOUT_DATA = 1;
	private FoodsService fs;
	private LocalesService ls;
	private TableLayout tableLayout;
	private EditText etKeyword;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IoCContainer ioc = App.get(this).getIoc();
		fs = ioc.getFs();
		ls = ioc.getLs();
		setContentView(R.layout.main);
		tableLayout = (TableLayout) findViewById(R.id.tableLayout);
		etKeyword = (EditText) findViewById(R.id.etKeyword);
		etKeyword.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			public void afterTextChanged(Editable s) {
				updateListing();
			}
		});
		updateListing();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString(KEY_KEYWORD, getKeyword());
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		setKeyword(savedInstanceState.getString(KEY_KEYWORD));
		updateListing();
	}

	private void setKeyword(String keyword) {
		etKeyword.setText(keyword);
	}

	private String getKeyword() {
		return etKeyword.getText().toString();
	}

	private void updateListing() {
		clearAll();
		String keyword = getKeyword();
		List<Food> foods = fs.findFoodRecommendations(keyword);
		for (Food food : foods) {
			Recommendation r = food.getRecommendation();
			String fullName = MessageFormat.format(
					getString(R.string.food_full_name_pattern), food.getName(),
					getString(food.getOrigin().getResId()), getString(food
							.getCult().getResId()));
			addRow(food.getId(), fullName, getString(r.getResId()), r
					.getColor());
		}
	}

	private void clearAll() {
		tableLayout.removeAllViews();
	}

	private void addRow(final Long id, String name, String recommendation,
			int color) {
		View r = getLayoutInflater().inflate(R.layout.tablerow, null);
		TextView tvName = (TextView) r.findViewById(R.id.tvName);
		tvName.setText(name);
		tvName.setTextColor(color);
		tvName.setClickable(true);
		tvName.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				nameClicked(id);

			}
		});
		TextView tvRecommendation = (TextView) r
				.findViewById(R.id.tvRecommendation);
		tvRecommendation.setText(recommendation);
		tvRecommendation.setTextColor(color);
		tableLayout.addView(r);
		getLayoutInflater().inflate(R.layout.separator, tableLayout);
	}

	private void nameClicked(Long id) {
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri
				.parse("food://" + id));
		intent.setClass(this, ShowFoodAct.class);
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.miExit:
			finish();
			return true;
		case R.id.miAboutProgram:
			showDialog(DLG_ABOUT_PROGRAM);
			return true;
		case R.id.miAboutData:
			showDialog(DLG_ABOUT_DATA);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DLG_ABOUT_PROGRAM:
			return createAboutProgramDialog();
		case DLG_ABOUT_DATA:
			return createAboutDataDialog();
		default:
			return null;
		}

	}

	private Dialog createAboutProgramDialog() {
		Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.about_text).setCancelable(true)
				.setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
		AlertDialog dlg = builder.create();
		return dlg;
	}

	private Dialog createAboutDataDialog() {
		Builder builder = new AlertDialog.Builder(this);
		WebView wvContent = new WebView(this);
		wvContent.loadUrl("file:///android_asset/aboutdata_"
				+ ls.getBestLocale().toString() + ".html");
		builder.setView(wvContent);
		builder.setCancelable(true).setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		AlertDialog dlg = builder.create();
		return dlg;
	}
}